const http = require('http');
const fs = require('fs');
const url = require('url');

//创建http服务器
const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);
    if(parsedUrl.pathname === '/'){
        fs.readFile('./index.html', (err, data) => {
            if(err){
                res.writeHead(500, {'Content-Type': 'text/plain'});
                res.end('服务器错误');
                return;
            }  
                res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
                res.end(data);
            })
    }
    else if(parsedUrl.pathname === '/movies'){
        http.get('http://maoyan.com/films', (movieRes) => {
            let html = '';

            //接收数据
            movieRes.on('data', (chunk) => {
                html += chunk;
            });
            //数据接收完毕，解析并返回结果
            movieRes.on('end', () => {
                const movies = parseMovies(html);
                res.writeHead(200,{
                    'Content-Type': 'application/json; charset=utf-8',
                    'Access-Control-Allow-Origin': '*'
                });
                res.end(JSON.stringify(movies));
        })
    }).on('error', (e) => {
        res.writeHead(500, {'Content-Type': 'application/json'});
        res.end(JSON.stringify({error: '获取电影数据失败' + e.message}));
    });
    }
    else{
        res.writeHead(404, {'Content-Type': 'text/plain'});
        res.end('未找到资源');
    }});
// 解析HTML获取电影数据
function parseMovies(html) {
  const movies = [];
  // 简单的字符串匹配方式提取数据（不使用第三方库）
  const movieItemRegex = /<div class="movie-item.*?data-val="(.*?)".*?<span class="movie-name">(.*?)<\/span>.*?<div class="movie-score.*?>(.*?)<\/div>/gs;
  
  let match;
  while ((match = movieItemRegex.exec(html)) !== null) {
    const id = match[1] ? match[1].trim() : '未知ID';
    const name = match[2] ? match[2].trim() : '未知名称';
    let score = match[3] ? match[3].trim().replace(/<.*?>/g, '') : '暂无评分';
    
    movies.push({ id, name, score });
  }
  
  return movies;
}

// 监听8081端口
server.listen(8081, () => {
  console.log('服务器运行在 http://localhost:8081');
});
